<template>
  <div>
    <el-upload
      :action="path"
      :headers="{ Authorization: token }"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :limit="limit"
      :before-upload="beforeAvatarUpload"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import config from '../plugins/config'
export default {
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      resourcesUrl: '',
      initEd: false,
      path: config.path + '/p/file/upload'
    }
  },
  props: {
    value: {
      default: '',
      type: String
    },
    // 最大上传数量
    limit: {
      default: 3,
      type: Number
    },
    fileList: {
      default:()=>[],
      type: Array
    }
  },
  computed: {
    token () { 
      return 'bearer' + Cookie.get('token')
    }
  },
  methods: {
    // 图片上传
    handleUploadSuccess (response, file, fileList) {
      this.resourcesUrl = file.response.resourcesUrl
      let pics = fileList.map(file => {
        return file.response.filePath
      }).join(',')
      this.$emit('input', pics)
    },
    // 限制图片上传大小
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error(this.$t('imageSizeCannotExceed2MB'))
        return false
      }

      // 判断图片类型来筛选图片格式上传
      let _type = file.type;
      if (_type.indexOf('png') == -1 && _type.indexOf('jpg') == -1 && _type.indexOf('jpeg') == -1) {
        this.$message.error(this.$t('imageNoformatUpload'))
        return false
      }
      return
    },
    handleRemove (file, fileList) {
      let pics = fileList.map(file => {
        return file.response
      }).join(',')
      this.$emit('input', pics)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style lang="scss">
</style>
